<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <a-transfer class='transfermodal' v-model:target-keys="targetKeys" v-model:selected-keys="selectedKeys"
      :data-source="dataSource" :render="item => item.title" @change="handleChange" :one-way="true" />
  </BasicModal>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { BasicModal, useModalInner } from '@/components/Modal'
import { getRoleList } from '@/api/sys/system'
import { divideRole } from '@/api/sys/user'

const getTitle = '角色授权';

defineOptions({ name: 'AccountAssignModal' })

const emit = defineEmits(['success', 'register'])
const dataSource = ref<any[]>([]);
const targetKeys = ref<string[]>([]);
const selectedKeys = ref<string[]>([]);

async function getRoleListForAll() {
  const ret = await getRoleList();
  const data: any[] = [];
  ret.forEach((item: any) => {
    data.push({
      key: item.roleId,
      title: item.roleName,
    })
  })
  dataSource.value = data;
}

onMounted(() => {
  getRoleListForAll()
});

const handleChange = (keys: string[], direction: string, moveKeys: string[]) => {
  console.log(keys, direction, moveKeys);
  selectedKeys.value = keys;
};

const rowId = ref('')

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  setModalProps({ confirmLoading: false })
  targetKeys.value = []
  selectedKeys.value = []
  // isUpdate.value = !!data?.isUpdate
  if (data.record.roleVoList) {
    targetKeys.value = data.record.roleVoList.map(item => item.roleId)
  }
  rowId.value = data.record.userId
})

async function handleSubmit() {
  try {
    // console.log(selectedKeys.value, rowId.value);
    await divideRole({
      userId: rowId.value,
      roleIdList: selectedKeys.value,
    })
    closeModal()
    emit('success')
  } finally {
    setModalProps({ confirmLoading: false })
  }
}

</script>

<style lang="less" scoped>
.transfermodal {
  justify-content: center;
}
</style>
